package main

import (
	"context"
	"fmt"
	"github.com/gorpher/gowin32/wrappers"
	log "github.com/sirupsen/logrus"
	"golang.org/x/sync/errgroup"
	"lanucher/config"
	"lanucher/global"
	"lanucher/signal"
)

var (
	sessionID uint32
	g         errgroup.Group
)

func main() {
	err := wrappers.ProcessIdToSessionId(wrappers.GetCurrentProcessId(), &sessionID)
	if err != nil {
		log.Error(err, "获取sessionID失败")
	}
	config.InitLog(fmt.Sprintf("%d", sessionID))
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	ctx = signal.WithContextFunc(ctx, func() {
		log.Error(err, "received signal, terminating process")
		cancel()
	})
	channel := NewVisualChannel()
	g.Go(func() error {
		err = channel.Serve(ctx)
		if err != nil {
			log.Error(err, "虚拟通道出错")
		}
		return err
	})
	g.Go(func() error {
		for {
			running := channel.running.Load()
			if running.(bool) {
				log.Debug("打开虚拟通道成功，发送会话win id")
				wToFrontend <- ChannelMsg{
					Code: global.ChannelMsgCodeForSayHi,
					Data: fmt.Sprintf("%d", sessionID),
				}
				return nil
			}
		}
	})

	err = g.Wait()
	if err != nil {
		log.Error(err, "launcher 退出")
	}
}
